/*****************************************************************************
 *
 * Copyright (C) 2003 CSHCN, University of Maryland.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Authors: Jonathan McGee <mcgee@umd.edu>
 *
 *****************************************************************************/
#include <linux/config.h>

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/notifier.h>
#include <asm/atomic.h>

#define CONFIG_PROC_FS
#include <linux/proc_fs.h>

#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <net/ip.h>

/* Root for our network output entries */
static struct proc_dir_entry *proc_netwrite = NULL;

/* Linked list of installed proc entries */
struct proc_netwrite_entry {
    struct proc_netwrite_entry *next;
    struct proc_dir_entry *entry;
    const char *devname;
    struct net_device *dev;
};

static struct proc_netwrite_entry *proc_netwrite_entries = NULL;

/*
 * Injecting packets into the IP stack
 */
static int proc_netwrite_write(struct file *file, const char *buffer,
        unsigned long count, void *data) {
    struct sk_buff *skb = NULL;
    struct iphdr *ip = (struct iphdr*)buffer;
    struct net_device *dev = NULL;

    /* Do some sanity checking */
    if(data == NULL) {
        printk(KERN_INFO __FILE__ ": %ld bytes written but no output "
                "device!\n", count);
        return -EPIPE;
    }

    /* Check data for basic sanity */
    if((count < sizeof(struct iphdr)) || (ip->version != 4)
            || (count > 0xFFFF)) {
        printk(KERN_INFO __FILE__ ": Packet so illegal, it's gonna be "
                "ignored.\n");
        return -EIO;
    }

    /* Get our device */
    dev = ((struct proc_netwrite_entry*)data)->dev;
    if(dev == NULL) {
        printk(KERN_DEBUG __FILE__ ": Odd, lost the output device.\n");
        return -EPIPE;
    }

    /* Make sure it's up */
    if(!netif_running(dev)) {
        printk(KERN_INFO __FILE__ ": Packet sent to down device %s\n",
                dev->name);
        return -EIO;
    }

    /* Create packet for sending */
    skb = dev_alloc_skb(count);
    if(skb == NULL) {
        printk(KERN_INFO __FILE__ ": Out of memory, cannot create sk_buff\n");
        return -ENOMEM;
    }

    /* Initialize data structure as necessary */
    ip = (struct iphdr*)skb_put(skb, count);
    memcpy(ip, buffer, count);

    skb->h.raw = NULL;
    skb->nh.iph = ip;
    skb->mac.raw = NULL;

    skb->pkt_type = PACKET_HOST;
    skb->protocol = __constant_htons(ETH_P_IP);
    skb->dev = dev;

    skb->ip_summed = CHECKSUM_NONE;
    skb->len = count;
    do_gettimeofday(&skb->stamp);

    /* "Receive" data */
    printk(KERN_DEBUG __FILE__ ": Feeding a %ld byte packet into the stack\n",
            count);
    ip_rcv(skb, skb->dev, NULL);
    return count;
}

/*
 * List behavior
 */

/* Add an item to the list */
static int proc_netwrite_addentry(struct net_device *dev) {
    struct proc_netwrite_entry *newentry;
    struct proc_dir_entry *newprocentry;

    /* Attempt to create proc entry */
    newprocentry = create_proc_entry(dev->name, S_IFREG|S_IRUGO|S_IWUSR,
            proc_netwrite);
    if(newprocentry == NULL) {
        return 1;
    }

    /* Allocate memory for data structure */
    newentry = kmalloc(sizeof(struct proc_netwrite_entry), GFP_ATOMIC);
    if(newentry == NULL) {
        remove_proc_entry(dev->name, proc_netwrite);
        return 1;
    }

    /* Initialize */
    newentry->next = NULL;
    newentry->entry = newprocentry;
    newentry->devname = dev->name;
    newentry->dev = dev;
    newprocentry->data = newentry;
    newprocentry->write_proc = proc_netwrite_write;

    /* Add to list */
    if(proc_netwrite_entries == NULL) {
        /* Empty list */
        proc_netwrite_entries = newentry;
    } else {
        /* Find end of list and link in */
        struct proc_netwrite_entry *head = proc_netwrite_entries;
        for(; head->next; head = head->next);
        head->next = newentry;
    }

    return 0;
}

/* Add all currently installed net devices to the list */
static int proc_netwrite_addallentries() {
    int err, errall = 0;
    struct net_device *curr = dev_base;

    while(curr) {
        err = proc_netwrite_addentry(curr);
        curr = curr->next;
        if(err) {
            errall = err;
        }
    }

    return errall;
}

/* Remove from list */
static int proc_netwrite_removeentry(struct net_device *dev) {
    struct proc_netwrite_entry *prev, *curr;

    /* Locate entry in list */
    prev = NULL;
    curr = proc_netwrite_entries;
    while(curr && (curr->dev != dev)) {
        prev = curr;
        curr = curr->next;
    }

    /* If we found it, remove it */
    if(curr) {
        /* Remove from list */
        if(prev) {
            prev->next = curr->next;
        } else {
            proc_netwrite_entries = curr->next;
        }
        /* Remove proc entry */
        curr->entry->data = NULL;
        remove_proc_entry(curr->devname, proc_netwrite);
        /* Clear it out in case proc file still open */
        curr->dev = NULL;
        curr->devname = NULL;
        kfree(curr);
    }

    return 0;
}

/* Remove all entries in the list */
static int proc_netwrite_removeallentries() {
    while(proc_netwrite_entries != NULL) {
        proc_netwrite_removeentry(proc_netwrite_entries->dev);
    }

    return 0;
}

/*
 * Keep our /proc up to date with network devices
 */
int on_device_notify(struct notifier_block *self, unsigned long event, void *v) {
    struct net_device *dev = (struct net_device*)v;
    switch(event) {
    case NETDEV_REGISTER:
        /* New device added to kernel */
        proc_netwrite_addentry(dev);
        break;

    case NETDEV_UNREGISTER:
        /* Device being removed from kernel */
        proc_netwrite_removeentry(dev);
        break;
    }
    return NOTIFY_DONE;
}

struct notifier_block device_event_notifier = {
    on_device_notify,
    NULL,
    0
};

/*
 * Called when the module is inserted in the kernel.
 */
int init_module()
{
    /* Create directory to hold our nodes */
    proc_netwrite = proc_mkdir("inject", proc_net);
    if(proc_netwrite == NULL) {
        /* Return failure if couldn't create the node */
        return 1;
    }
    /* Create the nodes for currently installed devices */
    proc_netwrite_addallentries();
    /* Be notified on device changes */
    register_netdevice_notifier(&device_event_notifier);
    return 0;
}

/*
 * Called when removing the module from memory... 
 */
void cleanup_module()
{
    /* Deregister entry into device notification */
    unregister_netdevice_notifier(&device_event_notifier);
    /* Remove existing devices */
    proc_netwrite_removeallentries();
    /* Remove node directory */
    remove_proc_entry("inject", proc_net);
}

MODULE_DESCRIPTION("MAODV Gateway kernel support.");
MODULE_AUTHOR("Jonathan McGee");
#ifdef MODULE_LICENSE
MODULE_LICENSE("GPL");
#endif
